<template>
  <div>
    <h1>{{$store.state.count}}</h1>
    <p>今年的年龄：{{$store.state.age}}</p>
    <p>今年的年龄：{{age}}</p>
    <p>明年的年龄：{{$store.getters.nextAge}}</p>
    <button @click="grown">过生日</button>
    <p>总金额：{{$store.getters.totalPrice}}</p>
    <p>总金额：{{totalPrice}}</p>
    <p>购物车数量{{$store.state.count}}</p>
    <el-button @click="addNum">+1</el-button>
    <p>账户余额：{{$store.state.money}}</p>
    <el-button type="danger" @click="chargeMoney({type: '$', num: 5})">充值</el-button>
    <hr>
    <p>我的积分：{{$store.state.point}}</p>
    <button @click="getPoint">更新积分(action)</button>
    <button @click="getPointSync">更新积分(mutation)</button>
    <p>我的等级：{{$store.state.level}}</p>
    <button @click="getLevel">更新等级(action)</button>
    <button @click="getLevelSync">更新等级(mutation)</button>
    <hr>
    <el-button type="danger" @click="getAct">action</el-button>
    <hr>
    <p>男生的年龄：{{$store.state.boy.age}}</p>
    <p>男生明年的年龄：{{$store.getters.nextAgeBoy}}</p>
    <p>女生的年龄：{{$store.state.girl.age}}</p>
    <p>女生明年的年龄：{{$store.getters.nextAgeGirl}}</p>
    <hr>
    <p v-for="(item, index) in list" :key="index">
      <router-link :to="'/goodsdetail/'+item.name">{{item.name}}</router-link>
    </p>
  </div>
</template>

<script>
// 辅助函数的作用：少按几次键，一个缩写形式。map就是映射，将数据从vuex中映射到组件里
import {mapState, mapGetters, mapMutations, mapActions} from 'vuex' // 1.从vuex中到如需要的辅助函数
import {BEOLD} from '../store/mutation_type'
export default {
  data() {
    return {
      list: [
        {name: '手机', price: 4000},
        {name: '电脑', price: 5000},
        {name: '手表', price: 1000},
        {name: '平板', price: 3000},
      ]
    }
  },
  computed: {
    // ...原来的计算属性正常写
    // totalPrice() {
    //   return 78
    // },
    // 这里写辅助函数,如果需要改名字就用对象的写法；不该名字就用字符串数组
    ... mapState({
      age: state => state.age
    }),
    ... mapGetters([
      'nextAge', 'totalPrice'
    ])
  },
  methods: {
    grown() {
      this.$store.commit(BEOLD)
    },
    ...mapMutations([
      'addNum', 'chargeMoney'
    ]),
    ...mapActions([
      'getPoint', 'getLevel'
    ]),
    getAct() {
      this.$store.dispatch('BEOLD')
    },
    // getPoint() {
    //   this.$store.dispatch('getPoint')
    // },
    // getLevel() {
    //   this.$store.dispatch('getLevel')
    // },
    getPointSync() {
      this.$http.get('/getpoint')
        .then(res => {
          // 到then里面就是同步了
          this.$store.commit('gotPoint', res.point);
        })  
    },
    async getLevelSync() {
      let num = await this.$http.get('/getlevel')
      commit('gotLevel', num)
    }
  }
}
</script>

<style>

</style>